<?php
declare (strict_types=1);

namespace app\user\controller;

use app\common\lib\queue\OperaShortUrl;
use app\common\model\VisitLog;
use app\user\model\ShortUrlLog;
use think\App;
use think\Exception;
use think\facade\Queue;

class User extends Ucenter
{
    protected $middleware = [
        \app\user\middleware\Login::class
    ];

    public function Ucenter()
    {
        $subQuery = ShortUrlLog::field('id')->where('user_id', $this->request->user->id)->buildSql();
        $data = [
            'username'            => cookie('username'),
            'today_set_num'       => ShortUrlLog::getTodaySetCount($this->request->user->id),
            'all_num'             => ShortUrlLog::getAllCount($this->request->user->id),
            'user'                => $this->request->user,
            'all_visit'           => VisitLog::where('url_id', 'in', $subQuery)->count(),
            'all_today_visit'     => VisitLog::where('url_id', 'in', $subQuery)->whereDay('create_time')->count(),
            'is_default_password' => false
        ];

        if (
            password_verify($this->request->user->email . '123456789', $this->request->user->password) ||
            password_verify($this->request->user->mobile . '123456789', $this->request->user->password)) {
            $data['is_default_password'] = true;
        }
        return $this->fetch('', ['data' => $data]);
    }

    public function links()
    {
        $pages = $this->request->get('pages/d', 1);
        $limit = $this->request->get('limit/d', 10);
        $list = ShortUrlLog::where('user_id', cookie('uid'))->page($pages)->limit($limit)->select();
        $count = ShortUrlLog::where('user_id', cookie('uid'))->count();
        return $this->fetch('', [
            'list'  => $list,
            'count' => $count,
            'end'   => $count / $limit,
            'pages' => $pages,
            'limit' => $limit
        ]);
    }

    public function delLinks()
    {

    }

    public function logout()
    {
        session('user', null);
        cookie('username', null);
        cookie('uid', null);
        cookie('email', null);

        return $this->response->success([], '已退出登录', '/user/login/login');
    }

    public function resetSecret()
    {
        try {
            $secret = $this->request->user->resetSecret();
            return $this->response->success($secret, '密匙已重置');
        } catch (\Exception $exception) {
            return $this->response->error($exception->getMessage());
        }
    }

    public function changeiplist()
    {
        $ip = $this->request->post('ip');
        $ipMap = explode("\r\n", $ip);
        foreach ($ipMap as $value) {
            if (!filter_var($value, FILTER_FLAG_IPV4) && filter_var($value, FILTER_FLAG_IPV6)) {
                return $this->response->error('[' . $value . ']不是一个正确的IP地址，请输入正确的ip地址');
            }
        }
        try {

            \app\user\model\User::modifyIpList(cookie('uid'), $ip);
            return $this->response->success([], 'ip白名单设置成功');
        } catch (\Exception $e) {
            return $this->response->error($e->getMessage());
        }
    }

    public function operaLinks()
    {
        $ids = $this->request->post('ids/a', []);
        $opera = $this->request->post('type/s', 'open');
        if ($opera == 'del') {
            if (!ShortUrlLog::where('id', 'in', $ids)->update(['delete_time' => time()])) {
                return $this->response->error('删除失败');
            }
        } else {
            $update = $opera == 'open' ? ['status' => ShortUrlLog::STATUS_NORMAL] : ['status' => ShortUrlLog::STATUS_FORBIDEN];
            if (!ShortUrlLog::where('id', 'in', $ids)->where('expire_time','>',time())->update($update)) {
                return $this->response->error('操作失败，选中的链接中可能含有已过期的');
            }
        }
        Queue::push(OperaShortUrl::class, ['ids' => $ids, 'opera'=>$opera], 'OPERA_SHORT_URL');
        return $this->response->success([], '操作成功');

    }

    public function userinfo()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['password'])) {
                unset($data['password']);
            } else {
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }
            if (\app\user\model\User::update($data, ['id' => cookie('uid')])) {
                return $this->response->success([], '信息已更新', 'userinfo');
            }
            return $this->response->error('信息更新失败');
        }
        return $this->fetch('', ['userinfo' => $this->request->user]);
    }
}
